<?php
/**
 * 更新小区total_number,sale_num
 */

namespace app\crontab\controller\always;


use custom\Log;
use custom\Redis;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Exception;

class HouseVillageCount extends Command {

    protected function configure() {
        $this->setName('HouseVillageCount');
    }

    protected function execute(Input $input, Output $output) {
        $this->initial();
    }

    public function initial() {
        echo "runing\n";
        try {
            //被房源关联了的小区id
            $vid = db('house')
                ->where('village_id', '>', 0)
//                ->where('city_codes', 'like', ',510000,510100%')
                ->group('village_id')
                ->column('village_id');
            foreach ($vid as $k => $v) {
                //拍卖总套数
                $total_num = Db::name('house')
                    ->alias('h')
                    ->leftJoin('house_auction ha', 'ha.id=h.auction_id')
                    ->where('h.is_shelf', 1)
                    ->where('h.deleted', 0)
                    ->where('h.village_id', $v)
                    ->count();
                //正在/即将拍卖套数
                $sale_num = Db::name('house')
                    ->alias('h')
                    ->leftJoin('house_auction ha', 'ha.id=h.auction_id')
                    ->where('ha.auction_status', 'in', [1, 2])
                    ->where('h.is_shelf', 1)
                    ->where('h.deleted', 0)
                    ->where('h.village_id', $v)
                    ->count();
                Db::name('house_village')
                    ->where('id', $v)
                    ->update([
                        'total_num' => $total_num,
                        'sale_num'  => $sale_num,
                    ]);
            }
        } catch (Exception $e) {
            Db::close();
            $err = $e->getMessage() . ' (' . $e->getCode() . '), ' . $e->getFile() . ' (' . $e->getLine() . ')' . "\n" . $e->getTraceAsString() . "\r\n\r\n";
            Log::write($err, "HouseVillageCountErr.log");
        }
        echo "end\n";
    }

}